package itsm.isperp.module.controller.api.mobile;

import itsm.isperp.framework.apk.ApkInfo;
import itsm.isperp.framework.apk.ApkUtils;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.FileUploadInfo;
import itsm.isperp.framework.domain.UploadInfo;
import itsm.isperp.framework.security.encoding.DESHelper;
import itsm.isperp.framework.service.UploadFileService;
import itsm.isperp.framework.upload.FilePersister;
import itsm.isperp.framework.utils.FileUploadParser;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.controller.incident.IcdIncidentController;
import itsm.isperp.module.controller.task.TskTaskController;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.service.app.AppMessageSuccessService;
import itsm.isperp.module.service.app.AppUploadFileService;
import itsm.isperp.module.service.app.AppUserService;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 
 * 手机端系统接口控制器
 * 
 * @author lizx
 * @date 2014-3-12
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("api/mobile/system")
public class MobileSystemController {

	public static final Logger logger = LoggerFactory
			.getLogger(MobileSystemController.class);

	@RequestMapping("loginValidate")
	@ResponseBody
	public ResultMessage loginValidate(String username, String password,
			HttpServletRequest req) {

		AppUserService appUserService = ContextHolder
				.getSpringBean(AppUserService.class);
		try {
			AppUser user = appUserService.findByUsername(username);
			if (user != null && password != null
					&& password.equals(DESHelper.decrypt(user.getPassword()))) {

				Map<String, Object> map = new HashMap<>();
				map.put("name", user.getName());
				map.put("fullname", user.getFullname());

				// String channelId = req.getParameter("channelId");
				// String userId = req.getParameter("userId");
				// int deviceType = Integer
				// .valueOf(req.getParameter("deviceType"));
				//
				// if (StringUtils.isNotEmpty(channelId)) {
				// appUserService.updatePushInfoByUsername(user.getId(),
				// userId, channelId, deviceType);
				// }

				return ResultMessage.success(user);
			} else {

				return ResultMessage.failure("用户名或密码错误");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure(e.getMessage());
		}
		
		//return ResultMessage.failure("请使用企业微信。");

	}

	@RequestMapping("updatePushInfo")
	@ResponseBody
	public ResultMessage updatePushInfo(String username, String userId,
			String channelId, int deviceType) {
		AppUserService appUserService = ContextHolder
				.getSpringBean(AppUserService.class);

		appUserService.updatePushInfoByUsername(username, userId, channelId,
				deviceType);
		return ResultMessage.success();
	}

	/**
	 * 登录验证
	 * 
	 * @param username
	 * @param password
	 * @param req
	 * @return
	 */
	@RequestMapping("login")
	@ResponseBody
	public ResultMessage login(String username, String password) {

		AppUserService appUserService = ContextHolder
				.getSpringBean(AppUserService.class);
		try {
			AppUser user = appUserService.findByUsername(username);
			if (user != null && password != null
					&& password.equals(DESHelper.decrypt(user.getPassword()))) {

				Map<String, Object> map = new HashMap<>();
				map.put("name", user.getName());
				map.put("fullname", user.getFullname());
				return ResultMessage.success(map);
			} else {

				return ResultMessage.failure("用户名或密码错误");
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure(e.getMessage());
		}

	}

	/**
	 * 获取待办事项
	 * 
	 * @param username
	 * @param req
	 * @return
	 */
	@RequestMapping("myTodoListCount")
	@ResponseBody
	public ResultMessage myTodoListCount(String username) {

		try {
			if (StringUtils.isNotEmpty(username)
					&& StringUtils.isNotBlank(username)) {

				Map<String, Object> map = new HashMap<>();

				// 获取消息
				AppMessageSuccessService appMessageSuccessService = ContextHolder
						.getSpringBean("appMessageSuccessService");
				map.put("message_count", appMessageSuccessService
						.findMyMessageCount(username, false));

				// 待办事件
				IcdIncidentController idIncidentController = ContextHolder
						.getSpringBean(IcdIncidentController.class);
				map.put("incident_count",
						idIncidentController.approvalCountByUsername(username));

				// 待办任务
				TskTaskController tskTaskController = ContextHolder
						.getSpringBean(TskTaskController.class);
				map.put("task_count",
						tskTaskController.approvalCountByUsername(username));

				return ResultMessage.success(map);
			} else {

				return ResultMessage.failure("用户名不能为空!");
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("系统无法获取待办事项,原因是:" + e.getMessage());
		}

	}

	/**
	 * 上传地理位置
	 * 
	 * @param username
	 * @param req
	 * @return
	 */
	@RequestMapping("uploadPositionInfo")
	@ResponseBody
	public ResultMessage uploadPositionInfo(String username, String longitude,
			String latitude) {

		AppUserService appUserService = ContextHolder
				.getSpringBean(AppUserService.class);
		try {
			AppUser user = appUserService.findByUsername(username);

			if (user != null) {

				// 更新工程师的地理位置
				user.setLongitude(longitude);
				user.setLatitude(latitude);
				Set<String> includeColumns = new HashSet<>();
				includeColumns.add("longitude");
				includeColumns.add("latitude");
				appUserService.saveOrUpdateSpecific(user, includeColumns);

				return ResultMessage.success("成功上传地理位置信息！");
			} else {

				return ResultMessage.failure("用户不存在！");
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("上传地理位置信息失败，原因是：" + e.getMessage());
		}

	}

	@RequestMapping("getApkUpdateInfo")
	@ResponseBody
	public ResultMessage getApkUpdateInfo() {

		String apkPath = ContextHolder.getApplicationPath()
				+ ContextHolder.getConfigByKey("apkFilePath");

		ApkInfo apk;
		try {
			apk = ApkUtils.getApkInfoByFilePath(apkPath);
			apk.setDownloadUrl(ContextHolder.getConfigByKey("apkFilePath"));
		} catch (Exception e) {
			return ResultMessage.failure(e.getMessage());
		}

		return ResultMessage.success(apk);
	}

	/**
	 * 获取附件信息
	 * 
	 * @param username
	 * @param req
	 * @return
	 */
	@RequestMapping("findFileInfo")
	@ResponseBody
	public ResultMessage findFileInfo(String sourceId) {

		AppUploadFileService appUploadFileService = ContextHolder
				.getSpringBean(AppUploadFileService.class);
		try {
			// to do
			JqGridRequest request = new JqGridRequest();
			request.setPageable(false);
			request.addFilterRule("source_id", JqGridFilterRuleOp.eq, sourceId);
			List<Map<String, Object>> list = appUploadFileService
					.findAllDetailByRequest(request);
			return ResultMessage.success(list);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("获取附件失败，原因是：" + e.getMessage());
		}

	}

	/**
	 * 上传文件
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST, value = "uploadFile")
	public ResultMessage uploadFile(HttpServletRequest req,
			HttpServletResponse resp) throws UnsupportedEncodingException {

		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");

		UploadFileService<UploadInfo> uploadFileService = ContextHolder
				.getSpringBean("appUploadFileService");
		FilePersister filePersister = ContextHolder
				.getSpringBean("isperp.filePersister");

		FileUploadParser parser = new FileUploadParser();
		FileUploadInfo fileUploadInfo = parser.parse(req);
		String sourceId = req.getParameter("sourceId");
		String username = req.getParameter("username");

		UploadInfo uploadInfo = ContextHolder
				.getSpringBean("isperp.uploadInfo");

		for (FileItem fileItem : fileUploadInfo.getFileItems()) {
			if (fileItem.getContentType() != null) {// 如果是文件类型

				uploadInfo.setId(HibernateUUIDGenerator.generate());
				uploadInfo.setSourceId(sourceId);
				fileUploadInfo.parseUploadInfo(fileItem.getName(), uploadInfo);

				// //将文件进行保存到目录在持久化操作
				try {
					filePersister
							.persist(fileItem.getInputStream(), uploadInfo);
				} catch (IOException e) {
					return ResultMessage.failure(e.getMessage());
				}
				if (StringUtils.isNotEmpty(sourceId)) {
					uploadInfo
							.setModifyDate(new Timestamp(new Date().getTime()));
					uploadInfo.setModifier(username);
					uploadInfo.setCreator(username);
					uploadFileService.saveOrUpdate(uploadInfo);
				}

				return ResultMessage.success(uploadInfo);

			}

		}

		return ResultMessage.failure();

	}

}
